{% extends "base.html" %}

{% block title %}服务更新{% endblock %}

{% block head %}
{{ super() }}
<!-- bootstrap-select -->
<link rel="stylesheet" href="/static/css/bootstrap-select.min.css">
{% endblock %}

{% block content %}
<!-- 页面头 -->
<section class="content-header">
  <!--头部标题-->
  <h1>
    服务更新
    <!--    <small>advanced tables</small>-->
  </h1>
  <!--面包屑-->
  <ol class="breadcrumb">
    <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>
    <li><a href="/job">工单审批</a></li>
    <li><a href="/job/type">新建工单</a></li>
    <li class="active">服务更新</li>
  </ol>
</section>

<!-- 页面内容 -->
<section class="content">
  <div class="row">
    <div class="col-md-12">

      <!-- 一般表单 -->
      <div class="box ">
<!--        <div class="box-header with-border">-->
<!--          <h3 class="box-title">填写服务详情</h3>-->
<!--        </div>-->
        <!-- /.box-header -->
        <!-- form start -->
        <form role="form" id="form">
          <div class="box-body">
            <div class="form-group">
              <label for="selectAuditor"><span style="color: red">*</span> 审批人</label>
              <select class="form-control" id="selectAuditor" name="auditor_id" required>
                <option value="" selected>--请选择--</option>
                {% for a in auditors %}
                <option value="{{a.id}}">{{a.name}}（{{a.comment}}）</option>
                {% endfor %}
              </select>
            </div>
            <div class="form-group">
              <label for="selectCluster"><span style="color: red">*</span> 集群</label>
              <select class="form-control" id="selectCluster" name="cluster_id" required>
                <option value="" selected>--请选择--</option>
                {% for cluster in clusters %}
                <option value="{{cluster.id}}">{{cluster.name}}</option>
                {% endfor %}
              </select>
            </div>
            <div class="form-group">
              <label for="selectNamespace"><span style="color: red">*</span> 命名空间</label>
              <select class="form-control" id="selectNamespace" name="namespace" required>
                <option value="">--请选择--</option>
              </select>
            </div>
            <div class="form-group">
              <label for="selectMicroservice"><span style="color: red">*</span> 微服务</label>
              <select class="selectpicker form-control" id="selectMicroservice" name="microservice"
                      data-live-search="true"
                      required>
                <option value="">--请选择--</option>
              </select>
            </div>
            <div class="form-group">
              <label for="oldImage">当前镜像</label>
              <p id="oldImage"></p>
            </div>
            <div class="form-group">
              <label for="newImage"><span style="color: red">*</span> 更新镜像<span style="color: red">（不能和当前镜像相同）</span></label>
              <input type="text" class="form-control" id="newImage" name="image" required>
            </div>

            <!--隐藏属性，发送工单类型-->
            <input class="hidden" type="text" class="form-control" name="type" value="1">

            <div class="form-group">
              <button type="button" class="btn btn-success" id="addBtn">添加到更新列表</button>&nbsp;&nbsp;&nbsp;
            </div>

            <div class="form-group">
              <label for="addList">更新列表:</label>
              <ul id="addList"></ul>
            </div>


          </div>
          <!-- /.box-body -->

          <div class="box-footer">
            <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#submitModal"
                    disabled="disabled"
                    id="submitBtn">提交
            </button>&nbsp;&nbsp;&nbsp;
          </div>
        </form>
      </div>
      <!-- /.box -->


    </div>
    <!-- /.col -->
  </div>
  <!-- /.row -->
</section>
<!-- /.页面内容 -->

<!--模态框：提交-->
<div class="modal fade" id="submitModal" tabindex="-1" role="dialog" aria-labelledby="submitModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
          aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="submitModalLabel">批量提交</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="message-text" class="control-label">更新说明:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-warning" id="modalSubmitBtn">提交</button>
      </div>
    </div>
  </div>
</div>
<!--模态框：提交，结束-->
{% endblock %}

{% block script %}

<script src="/static/js/bootstrap-select.min.js"></script>
<script type="text/javascript">
    // 定义全局变量
    var deploy
    var svcArray = []

    // 利用ajax提交表单，而不用submit默认提交方式
    // $('#saveBtn').click(function (e){
    //   if (cluster_id=='' || namespace=='' || microservice=='' || image=='' || risk=='') {
    //     bootbox.alert("有未填写的参数，请返回检查")
    //     return false
    //   }
    //   $.post('/api/v1/job/type-1/add', $('#form').serialize(), function (data) {
    //     if (data === 'success'){
    //       bootbox.alert('已保存到草稿箱。  您可以在此页面继续创建新的审批请求！', function () {
    //         $('#selectMicroservice').val("")
    //         $('.selectpicker').selectpicker('refresh');
    //         $('#oldImage').val("")
    //         $('#newImage').val("")
    //       })
    //     }
    //   });
    // })

    // 检测到未选择审批人，则隐藏提交按钮
    $("#selectAuditor").change(function () {
        var auditor_id = $('#selectAuditor').val();
        if (auditor_id === '') {
            $('#submitBtn').attr('disabled', 'disabled')
        } else if (svcArray.length > 0) {
            $('#submitBtn').removeAttr('disabled')
        }
    })

    // 检测命名空间选择变化，动态填充deploy名
    $("#selectNamespace").change(function () {
        console.log("namespace changed");
        $('#oldImage').text("")
        $('#newImage').val("")
        $('#selectMicroservice').val("")
        $('.selectpicker').selectpicker('refresh');
        $("#selectMicroservice").find('option').remove();
        $("#selectMicroservice").append('<option value="">--请选择--</option>');
        var current_cluster_id = $('#selectCluster').val().trim()
        var current_namespace = $("#selectNamespace").find("option:selected").text().trim()
        var url = '/api/cluster/' + current_cluster_id + '/' + current_namespace + '/deployments'
        if (current_namespace !== '--请选择--') {
            $.get(url, function (data) {
                console.log(data);
                deploy = data;
                for (let i in data['items']) {
                    $('#selectMicroservice').append('<option value="' + data['items'][i]['metadata']['name'] + '">' + data['items'][i]['metadata']['name'] + '</option>');
                }
                $('.selectpicker').selectpicker('refresh');
            })
        }
    })


    // 检测集群选择变化，动态填充命名空间
    $("#selectCluster").change(function () {
        console.log("cluster changed");
        $('#oldImage').text("")
        $('#newImage').val("")
        $('#selectMicroservice').val("")
        $('.selectpicker').selectpicker('refresh');

        var current_cluster_id = $('#selectCluster').val().trim()
        $("#selectNamespace").find('option').remove();
        $("#selectNamespace").append('<option value="">--请选择--</option>');
        $.get('/api/v1/cluster/' + current_cluster_id + '/namespaces', function (data) {
            for (var i in data.items) {
                $("#selectNamespace").append('<option value="' + data.items[i].metadata.name + '">' + data.items[i].metadata.name + '</option>');
            }
        });
    })


    // 检测到微服务变化，动态修改当前镜像字段
    $('#selectMicroservice').change(function () {
        console.log("microservice changed");
        $('#oldImage').text("")
        $('#newImage').val("")
        var name = $('#selectMicroservice').val();
        for (let i in deploy['items']) {
            if (deploy['items'][i]['metadata']['name'] === name) {
                setTimeout(function () {
                    $('#oldImage').text(deploy['items'][i]['spec']['template']['spec']['containers'][0]['image']);
                    $('#newImage').val(deploy['items'][i]['spec']['template']['spec']['containers'][0]['image']);
                }, 250)

                break;
            }
        }
    })

    // 检测到添加按钮
    $('#addBtn').click(function () {
        var auditor_id = $('#selectAuditor').val()
        var cluster_id = $('#selectCluster').val()
        var namespace = $('#selectNamespace').val()
        var microservice = $('#selectMicroservice').val()
        var image = $('#newImage').val()

        // 数据有效性校验
        if (auditor_id == '' || cluster_id == '' || namespace == '' || microservice == '' || image == '') {
            bootbox.alert("有未填写的参数，请返回检查")
            return false
        }
        if (image === $('#oldImage').text()) {
            bootbox.alert("镜像版本重复，请确认后重新输入！")
            return false
        }


        // 页面填充内容
        var text = '<li>'
        text += $('#selectCluster').find("option:selected").text() + ' | '
        text += $('#selectNamespace').find("option:selected").text() + ' | '
        text += $('#selectMicroservice').find("option:selected").text() + ' | '
        text += $('#newImage').val()
        text += '<button type="button" class="deleteMe btn btn-default btn-xs">删除</button>'
        text += '</li>'
        $('#addList').append(text)

        // 页面添加按钮开启
        $('#submitBtn').removeAttr('disabled')

        // 数组添加数据
        var svc = {cluster_id: cluster_id, namespace: namespace, microservice: microservice, image: image}
        // 将选择的服务加入全局数组svcArray
        svcArray.push(svc)
        console.log(svcArray)

        // 清除已选微服务
        $('#selectMicroservice').val("")
        $('.selectpicker').selectpicker('refresh');
        $('#oldImage').text("")
        $('#newImage').val("")

    })

    // 对于动态添加的按钮，jquery选择器无法直接获取，但可以用on方法获取
    $('#addList').on('click', ".deleteMe", function () {
        var index = $(this).parent().index()
        $(this).parent().remove() // 页面删除元素
        svcArray.splice(index, 1) // 数组删除元素
        console.log(svcArray)

        if (svcArray.length === 0) {
            $('#submitBtn').attr('disabled', 'disabled')
        }
    })


    $('#modalSubmitBtn').click(function (e) {
        e.preventDefault()
        console.log($('#message-text').val())
        var data = {
            type: 1,
            comment: $('#message-text').val(),
            svcArray: svcArray,
            auditor_id: $('#selectAuditor').val()
        }

        $.ajax({
            method: 'POST',
            url: '/api/v1/job/type-1/add',
            data: JSON.stringify(data),
            dataType: 'text',
            headers: {'Content-Type': 'application/json; charset=utf-8'},
            success: function (result) {
                $('#submitModal').modal('hide')
                bootbox.alert(result, function () {
                    if (result === 'success') {
                        setTimeout(function () {
                            location.href = '/job'
                        }, 250);
                    }
                });

            }
        })
    })


</script>
{% endblock %}